package com.artic.base.resourceloader;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

/**
 * A static API that can be used as a drop-in replacement for
 * java.lang.ClassLoader API (the class/resource loading part). This
 * implementation is merely a wrapper around
 * ClassLoaderResolverget.ClassLoader() method.
 * 
 * @author aczarnik
 */
public abstract class ResourceLoader {

	private static ClassLoader loader = ClassLoaderResolver.getClassLoader(1);

	/**
	 * @see java.lang.ClassLoader#loadClass(java.lang.String)
	 */
	public static Class<?> loadClass(final String name)
			throws ClassNotFoundException {
		return Class.forName(name, false, loader);
	}

	/**
	 * @see java.lang.ClassLoader#getResource(java.lang.String)
	 */
	public static URL getResource(final String name) {

		if (loader != null) {
			return loader.getResource(name);
		} else {
			return ClassLoader.getSystemResource(name);
		}
	}

	/**
	 * @see java.lang.ClassLoader#getResourceAsStream(java.lang.String)
	 */
	public static InputStream getResourceAsStream(final String name) {

		if (loader != null) {
			InputStream stream =  loader.getResourceAsStream(name);
                        if (stream == null){
                            stream = ClassLoader.getSystemResourceAsStream(name);
                        }
                        return stream;
		} else {
			return ClassLoader.getSystemResourceAsStream(name);
		}
	}

	/**
	 * @see java.lang.ClassLoader#getResources(java.lang.String)
	 */
	public static Enumeration<URL> getResources(final String name)
			throws IOException {

		if (loader != null) {
			return loader.getResources(name);
		} else {
			return ClassLoader.getSystemResources(name);
		}
	}

	private ResourceLoader() {
	} // prevent subclassing

	public static void setLoader(ClassLoader classloader) {
		loader = classloader;
	}

}